<?php
/**
 * 游戏表
 */
namespace Plu\Library\Models\Platform\Game;

use Phalcon\Mvc\Model,
    Phalcon\DI;

class GameCate extends Model {
    public $GameId;

    public $GameName;

    public $GameTag;

    public $GameSkin;

    public $ParentGameId;

    public $GamePath;

    public $GameLogoUrl;

    public $SortBy;

    public $CreateUser;

    public $CreateTime;

    public $UpdateUser;

    public $UpdateTime;

    public $DeleteUser;

    public $DeleteTime;

    public $DeleteFlag;

    const SKIN_TGA = 4;

    const SKIN_PLU = 2;

    public function initialize() {
        $this->setReadConnectionService('db.platform.slave');
    }

    public function getSource() {
        return "GameCate";
    }

    /**
     * 获取所有游戏数据
     */
    static public function getGames($skin) {
        $guid = sprintf('games_%s', $skin);

        $cache_handler = DI::getDefault()->get('cache');

        $items = $cache_handler->get($guid);

        if (empty($items)) {
            $data = self::find(array(
                'DeleteFlag = 0 AND GameId != 0 AND GameSkin & :skin: = :skin:',
                'bind'    => array(
                    'skin' => $skin
                )
            ));

            $data = $data->toArray();
            $items = array();
            $_subgames = array();
            array_walk($data, function($item) use (&$items, &$_subgames) {
                $parentid = $item['ParentGameId'];

                $items[$item['GameId']] = array(
                    'id'   => $item['GameId'],
                    'name' => $item['GameName'],
                    'tag'  => $item['GameTag'],
                    'logo' => $item['GameLogoUrl'],
                    'parentid' => $parentid
                );

                if ($parentid > 0) {
                    if (empty($_subgames[$parentid])) {
                        $_subgames[$parentid] = array(
                            'items' => array(),
                        );
                    }
                    $_subgames[$parentid]['items'][] = $item['GameId'];
                }
            });

            if (!empty($_subgames)) {
                foreach ($_subgames as $gameid => $data) {
                    if ($items[$gameid]) {
                        $items[$gameid]['subgames'] = $data['items'];
                        $items[$gameid]['subgames'][] = $gameid;
                    }
                }
            }

            $cache_handler->save($guid, $items);
        }

        return $items;
    }
}

?>
